{% extends "layout.html" %}

{% block content %}
<!-- 后端渲染的信号表，自动展示数据库signals表内容 -->
{% if signals %}
<div class="card mb-4">
  <div class="card-header">数据库信号表（自动刷新）</div>
  <div class="card-body p-0">
    <table class="table table-bordered table-striped mb-0">
      <thead>
        <tr>
          <th>序号</th>
          <th>信号日期</th>
          <th>股票编码</th>
          <th>状态</th>
          <th>盈亏</th>
        </tr>
      </thead>
      <tbody>
        {% for s in signals %}
        <tr>
          <td>{{ loop.index }}</td>
          <td>{{ s.signal_date }}</td>
          <td>{{ s.stock_code }}</td>
          <td>{{ s.status }}</td>
          <td>{{ s.pnl_pct }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</div>
{% endif %}

<div class="container-fluid">
    <!-- 横向表单容器 -->
    <div class="card">
        <div class="card-body">
            <div id="config-form-row" class="row g-3 align-items-center">
                <!-- 表单项和按钮将由JS动态生成到这里 -->
            </div>
        </div>
    </div>

    <!-- 结果区域 -->
    <div id="results-container" class="mt-4" style="display: none;">
        <hr>
        <h3>海选结果</h3>
        <div id="loading-spinner" style="display: none;" class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">正在计算中，请稍候...</p>
        </div>
        <div id="results-table-container">
            <!-- 结果表格将由JS动态生成 -->
        </div>
        <div id="pagination-container" class="d-flex justify-content-end align-items-center mt-3" style="display: none;">
            <span id="total-count-text" class="me-3 text-muted"></span>
            <div class="me-3">
                <select id="items-per-page-select" class="form-select form-select-sm" style="width: auto;">
                    <option value="10" selected>每页10条</option>
                    <option value="20">每页20条</option>
                    <option value="50">每页50条</option>
                    <option value="100">每页100条</option>
                </select>
            </div>
            <div id="pagination-controls">
                <!-- 分页控件将由JS动态生成 -->
            </div>
        </div>
    </div>
</div>

<!-- Modal for Trade Details -->
<div class="modal fade" id="tradeDetailModal" tabindex="-1" aria-labelledby="tradeDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tradeDetailModalLabel">交易详情: <span id="modal-stock-code"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 详细信息将加载到这里 -->
                <p>正在加载详情...</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const formRow = document.getElementById('config-form-row');
    let fullConfig = {}; // 用于存储完整的配置
    
    // --- 核心修改：使用后端注入的数据初始化信号列表 ---
    let allSignals = JSON.parse('{{ initial_signals_json | default("[]") | safe }}');
    
    let itemsPerPage = 10; // 每页显示条数
    let currentPage = 1;

    // --- 核心修改：页面加载时如果存在初始数据，则立即显示 ---
    if (allSignals && allSignals.length > 0) {
        const resultsContainer = document.getElementById('results-container');
        resultsContainer.style.display = 'block';
        displayCurrentPage();
    }

    // 为每页显示条数下拉框绑定事件
    const itemsPerPageSelect = document.getElementById('items-per-page-select');
    itemsPerPageSelect.addEventListener('change', function() {
        itemsPerPage = parseInt(this.value, 10);
        currentPage = 1; 
        displayCurrentPage();
    });

    // 获取配置并生成表单
    fetch('/api/get_config')
        .then(response => response.json())
        .then(config => {
            if (config.error) {
                formRow.innerHTML = `<div class="alert alert-danger">${config.error}</div>`;
                return;
            }
            fullConfig = config; 

            createFormElement('start_date', '开始日期', config.backtest_settings.start_date, 'date');
            createFormElement('end_date', '结束日期', config.backtest_settings.end_date, 'date');
            createFormElement('initial_cash', '初始资金', config.backtest_settings.initial_cash, 'number');
            createFormElement('trade_size', '交易股数', config.default_strategy_params.trade_size, 'number');
            createFormElement('force_recache', '强制更新缓存', config.data_settings.force_recache, 'checkbox');
            
            const btnContainer = document.createElement('div');
            btnContainer.className = 'col-auto';
            btnContainer.innerHTML = `<button id="start-backtest-btn" class="btn btn-primary"><i class="bi bi-play-fill"></i> 开始海选</button>`;
            formRow.appendChild(btnContainer);
            
            bindStartButtonEvent(); 
        })
        .catch(error => {
            console.error('Error fetching config:', error);
            formRow.innerHTML = `<div class="alert alert-danger">无法加载配置文件。</div>`;
        });

    // 创建单个表单元素的辅助函数
    function createFormElement(id, labelText, value, type = 'text') {
        const col = document.createElement('div');
        col.className = 'col-auto';
        let inputHtml = '';
        if (type === 'checkbox') {
            inputHtml = `<div class="form-check form-switch mt-2"><input class="form-check-input" type="checkbox" role="switch" id="param-${id}" name="${id}" ${value ? 'checked' : ''}><label class="form-check-label" for="param-${id}">${labelText}</label></div>`;
        } else {
             inputHtml = `<div class="input-group"><span class="input-group-text">${labelText}</span><input type="${type}" class="form-control" id="param-${id}" name="${id}"></div>`;
        }
        col.innerHTML = inputHtml;
        formRow.appendChild(col);
        
        setTimeout(() => {
            const input = col.querySelector(`#param-${id}`);
            if (input.type === 'date') {
                input.value = `${String(value).slice(0,4)}-${String(value).slice(4,6)}-${String(value).slice(6,8)}`;
            } else if (input.type !== 'checkbox') {
                 input.value = value;
            }
        }, 0);
    }

    // 绑定"开始海选"按钮事件
    function bindStartButtonEvent() {
        const startBtn = document.getElementById('start-backtest-btn');
        startBtn.addEventListener('click', function() {
            const resultsContainer = document.getElementById('results-container');
            const loadingSpinner = document.getElementById('loading-spinner');
            const tableContainer = document.getElementById('results-table-container');

            resultsContainer.style.display = 'block';
            loadingSpinner.style.display = 'block';
            tableContainer.innerHTML = ''; 
            document.getElementById('pagination-container').style.display = 'none';
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm"></span> 海选中...';

            const updatedConfig = JSON.parse(JSON.stringify(fullConfig));
            formRow.querySelectorAll('input').forEach(element => {
                const paramName = element.name;
                let value = (element.type === 'checkbox') ? element.checked : ((element.type === 'date') ? element.value.replace(/-/g, '') : (element.type === 'number' ? Number(element.value) : element.value));
                if (updatedConfig.data_settings.hasOwnProperty(paramName)) updatedConfig.data_settings[paramName] = value;
                else if (updatedConfig.backtest_settings.hasOwnProperty(paramName)) updatedConfig.backtest_settings[paramName] = value;
                else if (updatedConfig.default_strategy_params.hasOwnProperty(paramName)) updatedConfig.default_strategy_params[paramName] = value;
            });
            
            fetch('/api/run_signal_generation', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(updatedConfig),
            })
            .then(response => response.json())
            .then(result => {
                loadingSpinner.style.display = 'none';
                startBtn.disabled = false;
                startBtn.innerHTML = '<i class="bi bi-play-fill"></i> 开始海选';

                if (result.error) {
                    tableContainer.innerHTML = `<div class="alert alert-danger">海选失败: ${result.error}</div>`;
                    return;
                }
                
                allSignals = result.data || [];
                currentPage = 1;
                displayCurrentPage();
            })
            .catch(error => {
                console.error('Error during signal generation:', error);
                loadingSpinner.style.display = 'none';
                startBtn.disabled = false;
                startBtn.innerHTML = '<i class="bi bi-play-fill"></i> 开始海选';
                tableContainer.innerHTML = `<div class="alert alert-danger">请求失败，请检查网络或联系管理员。</div>`;
            });
        });
    }

    // 显示当前页数据和分页控件
    function displayCurrentPage() {
        const tableContainer = document.getElementById('results-table-container');
        const paginationControls = document.getElementById('pagination-controls');
        const totalCountText = document.getElementById('total-count-text');
        
        totalCountText.textContent = `共 ${allSignals.length} 条`;

        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const pageData = allSignals.slice(startIndex, endIndex);

        renderResultsTable(pageData, tableContainer);
        renderPagination(allSignals.length, paginationControls);
    }

    // 渲染分页控件
    function renderPagination(totalItems, container) {
        container.innerHTML = '';
        const totalPages = Math.ceil(totalItems / itemsPerPage);

        if (totalPages <= 1) {
            container.parentElement.style.display = 'none';
            return;
        }
        container.parentElement.style.display = 'flex';

        const nav = document.createElement('nav');
        const ul = document.createElement('ul');
        ul.className = 'pagination';

        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        const prevLink = document.createElement('a');
        prevLink.className = 'page-link';
        prevLink.href = '#';
        prevLink.textContent = '上一页';
        prevLink.addEventListener('click', (e) => { e.preventDefault(); if (currentPage > 1) { currentPage--; displayCurrentPage(); } });
        prevLi.appendChild(prevLink);
        ul.appendChild(prevLi);

        for (let i = 1; i <= totalPages; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            const link = document.createElement('a');
            link.className = 'page-link';
            link.href = '#';
            link.textContent = i;
            link.addEventListener('click', (e) => { e.preventDefault(); currentPage = i; displayCurrentPage(); });
            li.appendChild(link);
            ul.appendChild(li);
        }

        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        const nextLink = document.createElement('a');
        nextLink.className = 'page-link';
        nextLink.href = '#';
        nextLink.textContent = '下一页';
        nextLink.addEventListener('click', (e) => { e.preventDefault(); if (currentPage < totalPages) { currentPage++; displayCurrentPage(); } });
        nextLi.appendChild(nextLink);
        ul.appendChild(nextLi);

        nav.appendChild(ul);
        container.appendChild(nav);
    }

    // 【核心】渲染结果表格的辅助函数
    function renderResultsTable(data, container) {
        container.innerHTML = ''; 
        if (!allSignals || allSignals.length === 0) {
            container.innerHTML = '<div class="alert alert-info">在当前配置下，未发现任何买入信号。</div>';
            return;
        }

        const table = document.createElement('table');
        table.className = 'table table-striped table-hover';

        const thead = document.createElement('thead');
        const headerRow = document.createElement('tr');
        const headers = ["序号", "信号日期", "股票编码", "买入日期", "卖出日期", "盈亏", "状态", "操作"];
        headers.forEach(text => {
            const th = document.createElement('th');
            th.textContent = text;
            headerRow.appendChild(th);
        });
        thead.appendChild(headerRow);
        table.appendChild(thead);

        const tbody = document.createElement('tbody');
        data.forEach(item => {
            const row = document.createElement('tr');
            row.id = `signal-row-${item.id}`; // 为行设置唯一ID，便于后续更新
            
            const pnl = item.pnl ? item.pnl.toFixed(2) : '-';
            const pnl_pct = item.pnl_pct ? (item.pnl_pct * 100).toFixed(2) + '%' : '-';
            const pnlText = item.pnl ? `${pnl} (${pnl_pct})` : '-';
            const pnlClass = item.pnl > 0 ? 'text-danger' : (item.pnl < 0 ? 'text-success' : '');

            const status_map = {
                'Untested': {text: '未测评', class: 'bg-secondary'},
                'Tested': {text: '已测评', class: 'bg-success'}
            };
            const status_info = status_map[item.status] || status_map['Untested'];

            row.innerHTML = `
                <td>${item.序号}</td>
                <td>${item.signal_date}</td>
                <td>${item.stock_code}</td>
                <td class="buy-date">${item.buy_date || '-'}</td>
                <td class="sell-date">${item.sell_date || '-'}</td>
                <td class="pnl ${pnlClass}">${pnlText}</td>
                <td class="status"><span class="badge ${status_info.class}">${status_info.text}</span></td>
                <td class="action">
                    <button class="btn btn-sm btn-outline-primary view-details-btn" data-signal-id="${item.id}">
                        <i class="bi bi-search"></i> 查看
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        });
        table.appendChild(tbody);
        container.appendChild(table);

        // 为所有新的"查看"按钮绑定事件
        bindViewDetailsEvents();
    }

    // 【核心】为"查看"按钮绑定事件
    function bindViewDetailsEvents() {
        document.querySelectorAll('.view-details-btn').forEach(button => {
            // 先移除旧的监听器，防止重复绑定
            const newButton = button.cloneNode(true);
            button.parentNode.replaceChild(newButton, button);
            
            newButton.addEventListener('click', function() {
                const signalId = this.dataset.signalId;
                const row = document.getElementById(`signal-row-${signalId}`);
                const actionCell = row.querySelector('.action');
                
                // 进入加载状态
                this.disabled = true;
                this.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

                fetch(`/api/get_signal_details/${signalId}`)
                    .then(response => response.json())
                    .then(result => {
                        // 恢复按钮状态
                        this.disabled = false;
                        this.innerHTML = '<i class="bi bi-search"></i> 查看';

                        if (result.error) {
                            alert(`回测失败: ${result.error}`);
                            return;
                        }
                        
                        // 动态更新表格行
                        const pnl = result.pnl ? result.pnl.toFixed(2) : '-';
                        const pnl_pct = result.pnl_pct ? (result.pnl_pct * 100).toFixed(2) + '%' : '-';
                        const pnlText = result.pnl ? `${pnl} (${pnl_pct})` : '-';
                        const pnlClass = result.pnl > 0 ? 'text-danger' : (result.pnl < 0 ? 'text-success' : '');

                        row.querySelector('.buy-date').textContent = result.buy_date || '-';
                        row.querySelector('.sell-date').textContent = result.sell_date || '-';
                        row.querySelector('.pnl').textContent = pnlText;
                        row.querySelector('.pnl').className = `pnl ${pnlClass}`;
                        row.querySelector('.status').innerHTML = `<span class="badge bg-success">已测评</span>`;
                    })
                    .catch(error => {
                        console.error('Error fetching signal details:', error);
                        this.disabled = false;
                        this.innerHTML = '<i class="bi bi-search"></i> 查看';
                        alert('请求详细回测时发生网络错误。');
                    });
            });
        });
    }
});
</script>
{% endblock %} 